package com.lhy.service;


import cn.hutool.core.util.IdUtil;
import com.lhy.pojo.Miner;
import com.lhy.pojo.Record;
import com.lhy.pojo.User;
import com.mongodb.client.result.DeleteResult;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RecordService {

    @Resource
    private MongoTemplate mongoTemplate;

    //添加气体信息到mongodb
    public void addRecord(Record record){
        //生成气体编号
        record.setGasId(IdUtil.getSnowflake(1,1).nextIdStr());
        //更新时间
        record.setUpdateTime(new Date());
        //添加气体信息到mongodb
        mongoTemplate.insert(record,"record");
    }

    //查询所有用户
    public Map<String,Object> selectRecordList(){
        List<Record> list = mongoTemplate.findAll(Record.class,"record");
        Map<String,Object> userResult =new HashMap<>();

        if(list==null || list.isEmpty()){
            userResult.put("code","400");
            userResult.put("message","没有相关信息");
        }else{
            userResult.put("code","0");
            userResult.put("count",list.size());
            userResult.put("data",list);
        }
        return userResult;
    }

    //根据id删除
    public boolean deleteRecordById(String id){
        Query query = new Query(Criteria.where("gasId").is(id));
        DeleteResult result = mongoTemplate.remove(query, Record.class, "record");
        return result.getDeletedCount() >0 ? true : false;
    }

    //根据id修改气体信息
    public void updateRecordInfo(Record record){
        Query query = new Query(Criteria.where("gasId").is(record.getGasId()));
        Boolean exists = mongoTemplate.exists(query, Record.class, "record");

        if(exists==false) return;
        Update update=new Update();
        record.setUpdateTime(new Date());

        if(record.getGasName()!="") update.set("gasName",record.getGasName());

        if(record.getGasContent()!="") update.set("gasContent",record.getGasContent());

        if(record.getHarm()!="") update.set("harm",record.getHarm());

        if(record.getFeatures()!="") update.set("features",record.getFeatures());

        if(record.getSource()!="") update.set("source",record.getSource());

        if(record.getMeasure()!="") update.set("measure",record.getMeasure());

        mongoTemplate.upsert(query,update,Record.class,"record");
    }

    //通过气体名称查询
    public Record selectRecordByName(String gasName){
        Query query = new Query(Criteria.where("gasName").is(gasName));
        return mongoTemplate.findOne(query,Record.class,"record");
    }
}
